package com.cqeec.waimaidemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqeec.waimaidemo.common.CustomException;
import com.cqeec.waimaidemo.dto.SetmealDto;
import com.cqeec.waimaidemo.entity.Setmeal;
import com.cqeec.waimaidemo.entity.SetmealDish;
import com.cqeec.waimaidemo.mapper.SetmealMapper;
import com.cqeec.waimaidemo.service.SetmealDishService;
import com.cqeec.waimaidemo.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    /**
     * @param setmealDto
     */
    @Autowired
    SetmealDishService setmealDishService;
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> list=setmealDto.getSetmealDishes();
        list.forEach(x->x.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(list);
    }

    /**
     * @param ids
     */
    @Transactional
    @Override
    public void removeWithDish(List<Long> ids) {
//        查询状态是否可以删除
        LambdaQueryWrapper<Setmeal> wrapper =new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId,ids);
        wrapper.eq(Setmeal::getStatus,1);
        int count=this.count();
        if (count>0){
            throw new CustomException("套餐正在售卖，不可以删除");
        }
//        套餐没有再售卖就可以删除了
        this.removeByIds(ids);
//        删除setmealDish这张表的相关数据
        LambdaQueryWrapper<SetmealDish> wrapper1=new LambdaQueryWrapper<>();
        wrapper1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(wrapper1);
    }

}
